package part2.reflect;

import part2.reflect.annotations.AutoRunClass;
import part2.reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 调用与当前类Test6在同一个包中被注解@AutoRunClass标注的类中那些
 *     被注解@AutoRunMethod标注的方法若干次(次数由该方法注解的参数确定)
 */
public class Test6 {
    public static void main(String[] args) throws Exception{
        File file = new File(Test6.class.getResource(".").toURI());
        String packName = Test6.class.getPackage().getName();
        File[] subs = file.listFiles(f->f.getName().endsWith(".class"));
        for (File sub : subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName(packName+"."+className);
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int count = arm.value();
                        System.out.println("开始调用"+method.getName()+"()方法"+count+"次");
                        for (int i = 0; i < count; i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
